import Vue from 'vue'
import axios from 'axios'
// import store from '../vuex/store.js'
import router from '../router/router.js'
import { config as appConfig } from '../config.js'
import { Message  } from 'element-ui'
import { Loading } from 'element-ui';

// axios 配置
axios.defaults.baseURL =  appConfig.BASE_URL;
axios.defaults.timeout = 10000;
let loadingInstance = null;


// http request 请求拦截器，有token值则配置上token值
axios.interceptors.request.use(
    config => {
        var token = 'Bearer ' + localStorage.getItem(appConfig.TOKEN_KEY)
        config.headers.Authorization = token == 'Bearer' ? '' : token;
        // config.headers.common['Content-type'] = 'application/json;charset=UTF-8';

        // if(config.method == 'get'){
        //     loadingInstance = Loading.service({
        //         text: 'Loading',
        //         spinner: 'el-icon-loading',
        //         background: 'rgba(255, 255, 255, 0)'
        //     });
        // }else if(config.method == 'post'){
        //     loadingInstance = Loading.service({
        //         text: 'Loading',
        //         spinner: 'el-icon-loading',
        //         background: 'rgba(255, 255, 255, 0.6)'
        //     });
        // }


        return config;
    },
    err => {

        return Promise.reject(err);
    }
);

// http response 服务器响应拦截器，这里拦截401错误，并重新跳入登页重新获取token
axios.interceptors.response.use(
    response => {

        // loadingInstance.close();
        return response;
    },
    error => {
        // loadingInstance.close();
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    Message({
                        message: error.response.data.message,
                        type: 'warning'
                    });
                    router.replace({
                        path: '/',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    })
                case 404:
                    Message({
                        message: error.response.data.message,
                        type: 'warning'
                    });
                    router.replace({
                        path: '404',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    })
                case 500:
                    Message({
                        message: error.response.data.message,
                        type: 'warning'
                    });
                    router.replace({
                        path: '/',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    })
            }
        } else {
            Message({
                message: "网络连接异常，请稍后重试！",
                type: 'warning'
            });
        }
        return Promise.reject(error)
    }
);

export default axios;
